import { useI18n } from '@/hooks/web/useI18n'
import { reactive, ref, h } from 'vue'
import { CrudSchema } from '@/hooks/web/useCrudSchemas'
import { useValidator } from '@/hooks/web/useValidator'
import { SchemaConfig } from '@/api/global/types'
import { ElTag, ElSwitch, ElMessageBox } from 'element-plus'
import { statusApi } from '@/api/logisticsRules'
import { getSelectListApi } from '@/api/regionCountry'
import { getClassificationSelectListApi } from '@/api/logisticsClassification'
import { useEventBus } from '@/hooks/event/useEventBus'
import { useEnumeratePicker } from '@/utils'

const { t } = useI18n()
const { required } = useValidator()
const { emit } = useEventBus()

interface Option {
  label: string
  value: string | number
  disabled?: boolean
}

// 通用选项生成函数
const createOptions = (enumObject: { [key: string]: string }): Option[] => {
  return Object.keys(enumObject).map((key) => ({
    label: enumObject[key],
    value: parseInt(key, 10)
  }))
}

export default function (schemaConfig: SchemaConfig) {
  // 字段
  const warehouseOption = reactive(schemaConfig.fieldEnum?.warehouse || [])
  const termsOption = reactive(createOptions(schemaConfig.fieldEnum?.terms || {}))
  const statusOption = reactive(createOptions(schemaConfig.fieldEnum?.status || {}))
  const prescriptionOption = reactive(createOptions(schemaConfig.fieldEnum?.prescription || {}))

  prescriptionOption.map((item) => {
    if (item.value == 2) {
      item.disabled = true
    }
  })

  const classificationSelectList = ref<any[]>([])

  const getClassificationList = async () => {
    try {
      const res = await getSelectListApi({})
      if (res?.data) {
        classificationSelectList.value = res.data.list
      }
    } catch (error) {
      console.error('获取分类列表失败:', error)
    }
  }

  // 初始化时获取数据
  getClassificationList()

  const crudSchemas = reactive<CrudSchema[]>([
    {
      field: 'selection',
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        hidden: true
      },
      table: {
        type: 'selection'
      }
    },
    {
      field: 'id',
      label: t('logisticsRules.id'),
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        hidden: true
      }
    },
    {
      field: 'shipping_warehouse',
      label: t('logisticsRules.shipping_warehouse'),
      search: {
        component: 'TreeSelect',
        componentProps: {
          checkStrictly: true,
          filterable: true,
          data: warehouseOption
        }
      },
      form: {
        formItemProps: {
          rules: [required()]
        },
        component: 'TreeSelect',
        componentProps: {
          checkStrictly: true,
          filterable: true,
          data: warehouseOption
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            // 递归查找仓库名称
            const findWarehouseName = (list: any[], value: number): string => {
              for (const item of list) {
                if (item.value === value) return item.label
                if (item.children) {
                  const found = findWarehouseName(item.children, value)
                  if (found) return found
                }
              }
              return ''
            }
            return h('span', findWarehouseName(warehouseOption, data.shipping_warehouse))
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            // 递归查找仓库名称
            const findWarehouseName = (list: any[], value: number): string => {
              for (const item of list) {
                if (item.value === value) return item.label
                if (item.children) {
                  const found = findWarehouseName(item.children, value)
                  if (found) return found
                }
              }
              return ''
            }
            return h('span', findWarehouseName(warehouseOption, data.row.shipping_warehouse))
          }
        }
      }
    },
    {
      field: 'to_nation',
      label: t('logisticsRules.to_nation'),
      search: {
        component: 'Select',
        componentProps: {
          filterable: true,
          options: classificationSelectList
        }
      },
      form: {
        formItemProps: {
          rules: [required()]
        },
        component: 'Select',
        componentProps: {
          filterable: true,
          options: classificationSelectList
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.to_nation_name
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.to_nation_name
          }
        }
      }
    },

    {
      field: 'terms',
      label: t('logisticsRules.terms'),
      search: {
        component: 'Select',
        componentProps: {
          filterable: true,
          options: termsOption
        }
      },
      form: {
        component: 'Select',
        formItemProps: {
          rules: [required()]
        },
        componentProps: {
          filterable: true,
          options: termsOption
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return useEnumeratePicker(termsOption, data.terms)
          }
        }
      },
      table: {
        slots: {
          default: (data: any) => {
            return useEnumeratePicker(termsOption, data.row.terms)
          }
        }
      }
    },
    {
      field: 'prescription',
      label: '期望时效',
      search: {
        component: 'Select',
        componentProps: {
          filterable: true,
          options: prescriptionOption
        }
      },
      form: {
        component: 'Select',
        formItemProps: {
          rules: [required()]
        },
        componentProps: {
          options: prescriptionOption
        },
        value: 1
      },
      detail: {
        slots: {
          default: (data: any) => {
            return useEnumeratePicker(prescriptionOption, data.prescription)
          }
        }
      },
      table: {
        slots: {
          default: (data: any) => {
            return useEnumeratePicker(prescriptionOption, data.row.prescription)
          }
        }
      }
    },
    {
      field: 'execution_date',
      label: '执行时间',
      search: {
        hidden: true
      },
      form: {
        component: 'DatePicker',
        formItemProps: {
          rules: [required()]
        },
        componentProps: {
          type: 'datetime',
          valueFormat: 'YYYY-MM-DD HH:mm:ss',
          disabledDate: (time: Date) => time.getTime() < Date.now() - 8.64e7
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.execution_date
          }
        }
      },
      table: {
        slots: {
          default: (data: any) => {
            return data.row.execution_date
          }
        }
      }
    },
    {
      field: 'freight',
      label: t('logisticsRules.freight'),
      search: {
        hidden: true
      },
      form: {
        component: 'InputNumber',
        formItemProps: {
          rules: [
            required(),
            {
              validator: (rule, value, callback) => {
                console.log('value', value)
                if (value < 0) {
                  callback(new Error('运费值不合法'))
                } else {
                  callback()
                }
              },
              trigger: 'change'
            }
          ]
        },
        value: 0
      }
    },
    {
      field: 'surcharge_freight',
      label: t('logisticsRules.additionalCharges'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        componentProps: {
          type: 'number'
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.surcharge_freight
          }
        }
      }
    },
    {
      field: 'weight_lower',
      label: t('logisticsRules.weight_lower_fee'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        componentProps: {
          type: 'number'
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.weight_lower
          }
        }
      }
    },
    {
      field: 'notes',
      label: '备注',
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        componentProps: {
          type: 'textarea'
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.notes
          }
        }
      },
      table: {
        slots: {
          default: (data: any) => {
            return data.notes
          }
        }
      }
    },
    {
      field: 'status',
      fixed: 'right',
      width: '80',
      label: t('logisticsRules.status'),
      form: {
        component: 'Select',
        formItemProps: {
          rules: [required()]
        },
        componentProps: {
          options: statusOption
        },
        value: 1
      },
      search: {
        component: 'Select',
        componentProps: {
          options: statusOption,
          style: {
            width: '100%'
          }
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return (
              <ElTag type={data.status === 0 ? 'warning' : 'success'}>{data.status_value}</ElTag>
            )
          }
        }
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            const originalStatus = data.row.status // 保存原始状态
            const confirmationMessage = data.row.status === 1 ? '确定要关闭吗?' : '确定要开启吗?'
            const handleSwitchChange = () => {
              ElMessageBox.confirm(confirmationMessage, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              })
                .then(async () => {
                  const loading = ref(false)
                  loading.value = true
                  const res = await statusApi({
                    ids: data.row.id.toString(),
                    status: data.row.status
                  })
                    .catch(() => {})
                    .finally(() => {
                      loading.value = false
                    })
                  if (res) {
                    emit('getList', 'editor')
                  }
                })
                .catch(() => {
                  data.row.status = originalStatus
                })
            }
            return (
              <ElSwitch
                v-model={data.row.status}
                active-value={1}
                inactive-value={0}
                // active-text={statusOption[1].label}
                // inactive-text={statusOption[0].label}
                active-color="#13ce66"
                inactive-color="#ff4949"
                onChange={handleSwitchChange}
              ></ElSwitch>
            )
          }
        }
      }
    },
    // {
    //     field: 'create_time',
    //     label: t('logisticsRules.create_time'),
    //     search: {
    //         hidden: true
    //     },
    //     form: {
    //         hidden: true
    //     },
    //     table: {
    //         headerAlign: 'center',
    //         align: 'center'
    //     }
    // },
    // {
    //   field: 'creator',
    //   label: t('logisticsRules.creator'),
    //   search: {
    //     hidden: true
    //   },
    //   form: {
    //     hidden: true
    //   },
    //   detail: {
    //     slots: {
    //       default: (data: any) => {
    //         return data.creator_object?.cname ?? ''
    //       }
    //     }
    //   },
    //   table: {
    //     headerAlign: 'center',
    //     align: 'center',
    //     slots: {
    //       default: (data: any) => {
    //         return data.row.creator_object?.cname
    //       }
    //     }
    //   }
    // },
    {
      field: 'update_time',
      label: t('logisticsRules.update_time'),
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      table: {
        hidden: true
      }
    },
    {
      field: 'updater',
      label: t('logisticsRules.updater'),
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.updater_object?.cname ?? ''
          }
        }
      },
      table: {
        hidden: true
        // headerAlign: 'center',
        // align: 'center',
        // slots: {
        //   default: (data: any) => {
        //     return data.row.updater_object?.cname
        //   }
        // }
      }
    },
    {
      field: 'action',
      width: '260px',
      label: t('tableDemo.action'),
      fixed: 'right',
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return schemaConfig.actionButtonsTemplate?.template(data) ?? null
          }
        }
      }
    }
  ])

  return {
    crudSchemas
  }
}
